<template>
  <BoTable
    :columns="columns"
    :request="getLevelConfigList"
    ref="tableRef"
    height="auto"
    row-key="province"
  >
    <template #toolbars>
      <Space :size="8">
        <Button type="primary" @click="onAdd"> 新增 </Button>
      </Space>
    </template>
    <template #expandedRowRender="{ record, index }">
      <BoTable
        :columns="_columns"
        :request="async () => ({ rows: record.levelConfigVOList, total: 0 })"
        :ref="'tableExpandRef' + index"
        height="auto"
        row-key="id"
        hideSearch
        hidePagination
      >
        <template #intensity="{ record }">
          <Space>
            <Tag
              v-for="(item, index) in record.intensity
                ? record.intensity.split(',')
                : []"
              :key="index"
              :color="colorEnum[record.level as keyof typeof colorEnum]"
              style="color: #0c0c0c"
              >{{ item }}
            </Tag>
          </Space>
        </template>
      </BoTable>
    </template>
  </BoTable>

  <FormModal :columns="item" :model="openData"></FormModal>
</template>

<script setup lang="tsx">
import { computed, getCurrentInstance, ref } from 'vue';
import { useFormModal } from '@boeyo/hooks';
import { BoFormProps, BoTable, BoTableProps } from '@boeyo/ui';
import { Button, Modal, Space, Switch, Tag, message } from 'ant-design-vue';
import { pick } from 'lodash-es';
import {
  addLevelCofig,
  getLevelConfigList,
  getProvinceList,
  remove,
  updateLevelCofig,
} from './api';

const tableRef = ref();

const validator = (rule: any, value: any, callback: any) => {
  if (value) {
    for (let j = 1; j < value.length; j++) {
      console.log(value[j], Number(value[j - 1]) + 1, 'value[j]');
      if (Number(value[j]) != Number(value[j - 1]) + 1) {
        return Promise.reject('不连续');
      }
    }
  }
  return Promise.resolve();
};

const instance = getCurrentInstance();

const provinceOptions = ref<any[]>([]);
const getProvince = async () => {
  const res = await getProvinceList({});
  provinceOptions.value = res.data?.map((item) => {
    return {
      label: item,
      value: item,
    };
  });
};

getProvince();

const colorEnum = {
  无预警: '#808080',
  Ⅳ级: '#409EFF',
  Ⅲ级: '#ffff00',
  Ⅱ级: '#ffa500',
  Ⅰ级: '#ff0000',
};
const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '省份',
    dataIndex: 'province',
    hideInSearch: true,
  },
  {
    title: '是否默认配置',
    dataIndex: 'defaultFlag',
    valueType: 'status',
    hideInSearch: true,
    valueEnum: {
      1: {
        status: 'success',
        text: '默认',
      },
      0: {
        status: 'error',
        text: '非默认',
      },
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    actions(opt) {
      return [
        {
          text: '编辑',
          onClick(record) {
            onEdit(record, opt.index);
          },
        },
        {
          text: '删除',
          onClick(record) {
            Modal.confirm({
              title: '删除',
              content: '确定删除当前项吗？',
              okText: '确定',
              cancelText: '取消',
              onOk: async () => {
                await remove(record.name);
                tableRef.value.refresh();
              },
            });
          },
        },
      ];
    },
  },
]);
const _columns = computed<BoTableProps['columns']>(() => [
  {
    title: '烈度范围',
    dataIndex: 'intensity',
    width: 300,
  },
  {
    title: '预警等级',
    dataIndex: 'level',
  },
  {
    title: '等级颜色',
    dataIndex: 'levelColor',
  },
  {
    title: '避震指导',
    dataIndex: 'guidance',
  },
]);
const { FormModal, open } = useFormModal({
  size: 'small',
  column: 1,
});

const onEdit = async (record, index) => {
  console.log(record, 're');

  openData.value = record;
  if (Array.isArray(openData.value.levelConfigVOList)) {
    openData.value.levelConfigVOList.forEach((i, y) => {
      openData.value[`intensity${y}`] = i.intensity
        ? i.intensity.split(',')
        : [];
    });
  }
  open({
    title: '编辑',
    request: async (params: any) => {
      const queryParams = checkMiss(params);
      await updateLevelCofig(queryParams);
      tableRef.value.refresh();
      instance.refs[`tableExpandRef${index}`]?.refresh?.();
    },
    defaultValue: openData.value,
  });
};
const openData: any = ref({
  defaultFlag: '0',
});
const onAdd = () => {
  openData.value = {} as any;
  levelConfigDTOListTemplate().forEach((i, y) => {
    openData.value[`intensity${y}`] = i.intensity;
  });
  open({
    title: '新增',
    request: async (params: any) => {
      const queryParams = checkMiss(params);
      await addLevelCofig(queryParams);
      tableRef.value.refresh();
    },
    defaultValue: openData.value,
  });
};
const levelOption = [...Array(12)].map((_, i) => ({
  value: (i + 1).toString(),
}));

const item = computed<BoFormProps['columns']>(() => [
  {
    title: '配置名称',
    dataIndex: 'name',
    valueType: 'input',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入配置名称',
          trigger: 'blur',
        },
      ],
      wrapperCol: {
        span: '18',
      },
      labelCol: {
        span: '6',
      },
    },
    fieldProps: {
      placeholder: '请输入配置名称',
    },
  },
  {
    title: '无预警烈度范围',
    dataIndex: 'intensity0',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: false,
          message: '所选等级必须连续，不可跳选',
          validator,
          trigger: 'blur',
        },
      ],
      wrapperCol: {
        span: '18',
      },
      labelCol: {
        span: '6',
      },
    },
    fieldProps: {
      placeholder: '请选择无预警烈度范围',
      mode: 'multiple',
      options: levelOption,
      style: { '--alertLevel': 'grey', color: '#0c0c0c' },
      onChange(value: any, option) {
        processMethods(value, 'intensity0');
      },
    },
  },
  {
    title: '蓝色预警列度范围',
    dataIndex: 'intensity1',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: false,
          message: '所选等级必须连续，不可跳选',
          validator,
          trigger: 'blur',
        },
      ],
      wrapperCol: {
        span: '18',
      },
      labelCol: {
        span: '6',
      },
    },
    fieldProps: {
      placeholder: '请选择蓝色预警列度范围',
      mode: 'multiple',
      options: levelOption,
      style: { '--alertLevel': '#409EFF', color: '#0c0c0c' },
      onChange(value: any, option) {
        processMethods(value, 'intensity1');
      },
    },
  },
  {
    title: '黄色预警列度范围',
    dataIndex: 'intensity2',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: false,
          message: '所选等级必须连续，不可跳选',
          validator,
          trigger: 'blur',
        },
      ],
      wrapperCol: {
        span: '18',
      },
      labelCol: {
        span: '6',
      },
    },
    fieldProps: {
      placeholder: '请选择黄色预警列度范围',
      mode: 'multiple',
      options: levelOption,
      style: { '--alertLevel': 'yellow', color: '#0c0c0c' },
      onChange(value: any, option) {
        processMethods(value, 'intensity2');
      },
    },
  },
  {
    title: '橙色预警列度范围',
    dataIndex: 'intensity3',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: false,
          message: '所选等级必须连续，不可跳选',
          validator,
          trigger: 'blur',
        },
      ],
      wrapperCol: {
        span: '18',
      },
      labelCol: {
        span: '6',
      },
    },
    fieldProps: {
      placeholder: '请选择橙色预警列度范围',
      mode: 'multiple',
      options: levelOption,
      style: { '--alertLevel': 'orange', color: '#0c0c0c' },
      onChange(value: any, option) {
        processMethods(value, 'intensity3');
      },
    },
  },
  {
    title: '红色预警列度范围',
    dataIndex: 'intensity4',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: false,
          message: '所选等级必须连续，不可跳选',
          validator,
          trigger: 'blur',
        },
      ],
      wrapperCol: {
        span: '18',
      },
      labelCol: {
        span: '6',
      },
    },
    fieldProps: {
      placeholder: '请选择红色预警列度范围',
      mode: 'multiple',
      options: levelOption,
      style: { '--alertLevel': 'red', color: '#0c0c0c' },
      onChange(value: any, option) {
        processMethods(value, 'intensity4');
      },
    },
  },
  {
    title: '默认配置',
    dataIndex: 'defaultFlag',
    valueType: 'switch',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择是否为默认配置',
          trigger: 'blur',
        },
      ],
      wrapperCol: {
        span: '18',
      },
      labelCol: {
        span: '6',
      },
    },
    fieldProps: {
      unCheckedValue: '0',
      unCheckedChildren: '否',
      checkedValue: '1',
      checkedChildren: '是',
    },
  },
  {
    title: '省份',
    dataIndex: 'province',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择省份',
          trigger: 'blur',
        },
      ],
      wrapperCol: {
        span: '18',
      },
      labelCol: {
        span: '6',
      },
    },
    fieldProps: {
      placeholder: '请选择省份',
      options: provinceOptions.value,
    },
  },
]);

const levelConfigDTOListTemplate = () => [
  {
    intensity: ['1', '2'],
    level: '无预警',
    levelColor: '无预警（灰色）',
    guidance: '此次地震无影响',
  },
  {
    intensity: ['3', '4', '5'],
    level: 'Ⅳ级',
    levelColor: '蓝色预警',
    guidance: '有感地震，注意观察',
  },
  {
    intensity: ['6', '7', '8'],
    level: 'Ⅲ级',
    levelColor: '黄色预警',
    guidance: '有感地震，注意防范',
  },
  {
    intensity: ['9', '10'],
    level: 'Ⅱ级',
    levelColor: '橙色预警',
    guidance: '强烈地震，立即避险',
  },
  {
    intensity: ['11', '12'],
    level: 'Ⅰ级',
    levelColor: '红色预警',
    guidance: '破坏地震，紧急避险',
  },
];

const processMethods = (value, intensity) => {
  for (const key in openData.value) {
    if (!key.includes('intensity') || key === intensity) continue;
    openData.value[key].forEach((i) => {
      if (value.includes(i)) {
        const index = openData.value[key].findIndex((a) => a == i);
        openData.value[key].splice(index, 1);
      }
    });
  }
  openData.value[intensity] = value.sort((a, b) => a - b);
};

const checkMiss = (params) => {
  let result = [];
  for (const key in params) {
    if (!key.includes('intensity')) continue;
    result = result.concat(params[key]);
  }
  if (result.length !== levelOption.length) {
    message.warning('等级有缺漏，请检查选择等级');
    throw new Error('等级有缺漏，请检查选择等级');
  }
  params['levelConfigDTOList'] = levelConfigDTOListTemplate().map((i, y) => {
    return {
      ...i,
      intensity: params[`intensity${y}`].join(),
      id: params['levelConfigVOList']?.[y]?.id || '',
    };
  });
  const queryParams = pick(params, [
    'levelConfigDTOList',
    'defaultFlag',
    'name',
    'province',
  ]);
  return queryParams;
};
</script>

<style lang="scss">
.ant-select-multiple {
  .ant-select-selection-item {
    background-color: var(--alertLevel, #f0f0f0) !important;
  }
}
</style>
<route lang="json">
{
  "name": "预警等级配置",
  "meta": {
    "title": "预警等级配置"
  }
}
</route>
